package com.example.homework;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.homework.model.User;

public class LoginActivity extends AppCompatActivity {
    private EditText nameEdit;
    private EditText passwordEdit;
    private CheckBox rememberCheck;
    private Button loginButton;
    private DBHelper dbHelper;
    private TextView registerButton;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        setTitle("登录");
        this.nameEdit=findViewById(R.id.name_edit);
        this.passwordEdit=findViewById(R.id.password_edit);
        this.rememberCheck=findViewById(R.id.remember_check);
        this.loginButton=findViewById(R.id.login_button);
        this.dbHelper=new DBHelper(this);
        this.registerButton=findViewById(R.id.register_button);
        fillRemember();
        this.registerButton.setOnClickListener(v->{
            Intent intent=new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
        this.loginButton.setOnClickListener(v->{
            String name=nameEdit.getText().toString();
            String password=passwordEdit.getText().toString();
            User user=dbHelper.findByName(dbHelper.getReadableDatabase(),name);
            if (user==null){
                Toast.makeText(this,"用户不存在",Toast.LENGTH_SHORT).show();
            }else{
                if (user.getPassword().equals(password)){
                    SharedPreferences.Editor sharedPreferences=getSharedPreferences("remember",MODE_PRIVATE).edit();
                    if(rememberCheck.isChecked()){
                        sharedPreferences.putString("name",name);
                        sharedPreferences.putString("password",password);
                    }else{
                        sharedPreferences.clear();
                    }
                    sharedPreferences.apply();

                    Intent intent=new Intent(this, MainActivity.class);
                    startActivity(intent);
                }else{
                    Toast.makeText(this,"密码错误",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void fillRemember(){
        SharedPreferences sharedPreferences=getSharedPreferences("remember",MODE_PRIVATE);
        String name=sharedPreferences.getString("name","");
        String password=sharedPreferences.getString("password","");
        this.nameEdit.setText(name);
        this.passwordEdit.setText(password);
    }
}
